package com.xhs.repository;

import com.xhs.entity.Content;
import com.xhs.entity.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 内容数据访问接口
 */
@Repository
public interface ContentRepository extends JpaRepository<Content, Long> {
    
    /**
     * 根据作者查找内容（分页）
     */
    Page<Content> findByAuthorAndPublishedTrueOrderByCreatedAtDesc(User author, Pageable pageable);
    
    /**
     * 查找已发布的内容（分页）
     */
    Page<Content> findByPublishedTrueOrderByCreatedAtDesc(Pageable pageable);
    
    /**
     * 根据标题搜索内容（分页）
     */
    @Query("SELECT c FROM Content c WHERE c.published = true AND c.title LIKE %:keyword% ORDER BY c.createdAt DESC")
    Page<Content> findByTitleContainingAndPublishedTrue(@Param("keyword") String keyword, Pageable pageable);
    
    /**
     * 根据点赞数排序推荐内容（排除已访问的内容）
     */
    @Query("SELECT c FROM Content c WHERE c.published = true AND c.id NOT IN " +
           "(SELECT vh.content.id FROM ViewHistory vh WHERE vh.user = :user) " +
           "ORDER BY c.likeCount DESC, c.createdAt DESC")
    Page<Content> findRecommendedContentsExcludingViewed(@Param("user") User user, Pageable pageable);
    
    /**
     * 根据点赞数排序推荐内容（未登录用户）
     */
    @Query("SELECT c FROM Content c WHERE c.published = true ORDER BY c.likeCount DESC, c.createdAt DESC")
    Page<Content> findRecommendedContents(Pageable pageable);
    
    /**
     * 获取内容的上一个和下一个
     */
    @Query("SELECT c FROM Content c WHERE c.published = true AND c.id > :currentId ORDER BY c.id ASC")
    List<Content> findNextContent(@Param("currentId") Long currentId, Pageable pageable);
    
    @Query("SELECT c FROM Content c WHERE c.published = true AND c.id < :currentId ORDER BY c.id DESC")
    List<Content> findPreviousContent(@Param("currentId") Long currentId, Pageable pageable);
    
    /**
     * 根据内容类型查找
     */
    Page<Content> findByTypeAndPublishedTrueOrderByCreatedAtDesc(Content.ContentType type, Pageable pageable);
    
    /**
     * 获取用户的所有内容（包括未发布的）
     */
    Page<Content> findByAuthorOrderByCreatedAtDesc(User author, Pageable pageable);
} 